<?php
/**
 * @file article.php $
 * @author LinLin (linlin@haibao.com) $
 * @date 2015年8月5日 下午14:49:50 $
 * @brief app 文章列表 $
 */
namespace haibao\app\business;

use haibao\app\model\data\Article as ArticleData;
use haibao\app\data\ArticleProperty as ArticlePropertyData;
use haibao\frame\data\datafield\DateField;

class Article extends \haibao\app\business\Base {
	
    
	/**
	 * @var $_instance
	 */
	private static $_instance;
	
	/**
	 * instance()
	 */
	private static function instance(){
		if(!self::$_instance){
			self::$_instance = new \haibao\app\data\Article();
		}
		return self::$_instance;
	}
	
	/**
	 * 获取文章列表
	 */
	public static function getArticleList($query){
		return self::instance()->getAll($query);
	}
	
	public static function getOneArticle($query){
		return self::instance()->getOne($query);
	}
	
	public static function getArticleById($articleId){
	    return self::instance()->getOneById($articleId);
	}
	
	/**
	 * 根据文章名模糊查询文章
	 */
	public static function getArticleByTitle($name){
	    return self::instance()->getArticleByTitle($name);
	}
	
	/**
	 * 得题图ID
	 * @param unknown_type $articleId
	 */
	public static function getArticleImageId($articleId){
		return self::instance()->getArticleImageId($articleId);
	}
	
	/**
	 * 通过文章ID获取内容图片ID
	 */
	public static function getArticleImagesId($articleId){
	    return self::instance()->getArticleImagesId($articleId);
	}
	
	/**
	 * 通过ID得到单条文章数据
	 */
	public static function getArticleInfo($articleId){
		if(empty($articleId)){
			throw new BusinessException('文章ID不能为空');
		}
		return self::instance()->getOneArticleById($articleId);
	}
	
	public static function getArticleTagList($articleId){
	    if(!$articleId){
	        throw new BusinessException('文章ID不能为空');
	    }
	    if($fashion = self::instance()->getFashionByArticleId($articleId)){
	        foreach($fashion as $key=>$value){
	            $tmpArr['tagId'] = $value['Id'];
	            $tmpArr['tagName'] = $value['NameCN'];
	            $tmpArr['tagType'] = '5';
	            unset($fashion[$key]);
	            $fashion[$key] = $tmpArr;
	        }
	    }
	    if($brand = self::instance()->getBrandByArticleId($articleId)){
	       foreach($brand as $key=>$value){
	       		if(!empty($value['BrandName']) || !empty($value['BrandNameEN'])){
	       			$tmpArr['tagId'] = $value['BrandId'];
	       			$tmpArr['tagName'] = $value['BrandName'] ? $value['BrandName'] : $value['BrandNameEN'];
	       			$tmpArr['tagType'] = '4';
	       			$brand[$key] = $tmpArr;
	       		} else {
	       			unset($brand[$key]);
	       		}
	        }
	    }
	    if($star = self::instance()->getStarByArticleId($articleId)){
	        foreach($star as $key=>$value){
	        	if(!empty($value['StarName']) || !empty($value['StarNameEn'])){
	        		$tmpArr['tagId'] = $value['StarId'];
		            $tmpArr['tagName'] = $value['StarName'] ? $value['StarName'] : $value['StarNameEn'];
		            $tmpArr['tagType'] = '3';
		            unset($star[$key]);
		            $star[$key] = $tmpArr;
	        	} else {
	        		unset($star[$key]);
	        	}
	        }
	    }
	    if($event = self::instance()->getEventByArticleId($articleId)){
	       foreach($event as $key=>$value){
	            $tmpArr['tagId'] = $value['EventId'];
	            $tmpArr['tagName'] = $value['EventName'];
	            $tmpArr['tagType'] = '6';
	            unset($event[$key]);
	            $event[$key] = $tmpArr;
	        }
	    }
	    return array(
	        'fashion' => $fashion,
	        'star' => $star,
	        'brand' => $brand,
	        'event' => $event,
	    );
	}
	
	public static function getOneArticleById($articleId){
		$article = self::instance()->getOneArticleById($articleId);
		
		$article['Image'] = self::instance()->getArticleImage($articleId);
		$article['Column'] = self::instance()->getArticleColumn($articleId);
		$article['Vote'] = self::instance()->getArticleVote($articleId);
		$article['Star'] = self::instance()->getStarByArticleId($articleId);
		$article['Brand'] = self::instance()->getBrandByArticleId($articleId);
		$article['Fashion'] = self::instance()->getFashionByArticleId($articleId);
		$article['Area'] = self::instance()->getAreaByArticleId($articleId);
		$article['Event'] = self::instance()->getEventByArticleId($articleId);
		$article['StarTag'] = self::instance()->getRelatedTagByArticleId($articleId,\haibao\app\model\data\Article::STAR_TAG);
		$article['BrandTag'] = self::instance()->getRelatedTagByArticleId($articleId,\haibao\app\model\data\Article::BRAND_TAG);
		$article['FashionTag'] = self::instance()->getRelatedTagByArticleId($articleId,\haibao\app\model\data\Article::FASHION_TAG);
		$article['EventTag'] = self::instance()->getRelatedTagByArticleId($articleId,\haibao\app\model\data\Article::EVENT_TAG);
		
		return $article;
	}
	
	/**
	 * 通过文章ID获取cms图片信息
	 */
	public static function productAppArticle($articleId){
	   $imageArr = \haibao\cms\business\Article::getArticleImageById($articleId); //cms imageid
	   if($imageArr){
	       $appImage = array();
	       foreach($imageArr as $key=>$val){
	           $imageId[$val] = '';
	       }
	       list($cmsImageIds,$cmsImageInfo) = \haibao\app\business\ImageLibrary::addPcImageToApp($imageArr);//添加到APP图片库   返回imageid
	       $appNewImageInfo = \haibao\app\business\ImageLibrary::getImageByIds($cmsImageIds); //app imagelibrary库 信息
	       $article = new \haibao\cms\common\ArticleContent();
	       foreach($cmsImageInfo as $key=>$value){
	           $appImageInfo[$key]['Id'] = $value->Id;
	           $appImageInfo[$key]['ArticleId'] = $articleId;
	           $appImageInfo[$key]['FileName'] = $value->Filename;
	           $imgUrl = $value->Filename;
	           $appImageInfo[$key]['CDN_imageUrl_600'] = $article->replaceImageLink($imgUrl, 600, 0, 100, 0);
	           $appImageInfo[$key]['Type'] = \haibao\app\model\data\ImageLibrary::IMAGE_TYPE_PERSON;
	       }
	       foreach($imageId as $key=>$val){
	           foreach($appImageInfo as $k=>$v){
	               if($key == $v['Id']){
	                   $appImage[$key] = $v;
	               }
	           }
	       }
	       foreach($appImage as $key=>$info){
	           foreach($appNewImageInfo as $k=>$v){
	               if($info['FileName'] == $v['Filename']){
	                   $appImage[$key]['Id'] = $v['Id'];
	               }
	           }
	       }
	   }else{
	       $appImage = $cmsImageIds = array();
	   }
	   return array($appImage,$cmsImageIds);
	}
	
	/**
	 * 通过文章ID获取app图片信息
	 */
	public static function productPCArticle($articleId){
	    $imageArr = \haibao\app\business\Article::getArticleImagesId($articleId); //app imageid
	    if($imageArr){
	        $appImage = array();
	        foreach($imageArr as $key=>$val){
	            $imageId[$val] = '';
	        }
	        list($cmsImageIds,$cmsImageInfo) = \haibao\cms\business\ImageLibrary::addAppImageToPc($imageArr);//添加到CMS图片库   返回imageid  cms库的图片id
	        $appNewImageInfo = \haibao\cms\business\ImageLibrary::getImagesById($cmsImageIds); //cms imagelibrary库 信息
	        $article = new \haibao\cms\common\ArticleContent();
	        foreach($cmsImageInfo as $key=>$value){
	            $appImageInfo[$key]['Id'] = $value->Id;
	            $appImageInfo[$key]['ArticleId'] = $articleId;
	            $appImageInfo[$key]['FileName'] = $value->Filename;
	            $imgUrl = $value->Filename;
	            $appImageInfo[$key]['CDN_imageUrl_600'] = $article->replaceImageLink($imgUrl, 600, 0, 100, 0);
	        }
	        foreach($imageId as $key=>$val){
	            foreach($appImageInfo as $k=>$v){
	                if($key == $v['Id']){
	                    $appImage[$key] = $v;
	                }
	            }
	        }
	        foreach($appImage as $key=>$info){
	            foreach($appNewImageInfo as $k=>$v){
	                if($info['FileName'] == $v->Filename){
	                    $appImage[$key]['Id'] = $v->Id;
	                }
	            }
	        }
	    }else{
	        $appImage = $cmsImageIds = array();
	    }
	    return array($appImage,$cmsImageIds);
	}
	
	
	
	
	public static function addArticlePcToApp($model){
	    $model->ImageId =  0;
	    $model->CreateTime =  new \DateTime();
	    $model->PublishTime = new \DateTime();
	    $model->Published =  \haibao\app\model\data\Article::PUBLISHED_NO;
	    $model->Author = self::getCurrentUser()->RealName;
	    $model->Status =  \haibao\app\model\data\Article::STATUS_ENABLE;
	    $model->CreateBy = self::getCurrentUser()->Id;
	    $model->Type = \haibao\app\model\data\Article::TYPE_ARTICLE;
	    self::instance()->addArticlePcToApp($model);
	}
	
	/**
	 * 街拍PC 获取列表页
	 */
	public static function getAppOneArticleById($articleId){
		$article = self::instance()->getOneArticleById($articleId);
		$article['Column'] = self::instance()->getArticleColumn($articleId);
		return $article;
	}
	
	public static function getActivityType($activityId){
		return self::instance()->getActivityType($activityId);
	}
	
	public static function getOneById($articleId){
		if(!$articleId){
			throw new BusinessException('文章ID不能为空');
		}
		return self::instance()->getOneById($articleId);
	}
	
	/**
	 * 更新文章
	 * @param \haibao\app\model\data\Article $model
	 */
	public static function saveArticle($model){
		self::checkOperation(self::FUNC_CODE_APP_ARTICLE_SAVE);
		self::checkForm($model);
		self::convertData($model);
		
		if(!$model->Id){
			$model->CreateBy = self::getCurrentUser()->Id;
			$model->Author = self::getCurrentUser()->RealName;
			$model->CreateTime  = new \DateTime();
			$model->Type = ArticleData::TYPE_ARTICLE;
		}else {
			$article = self::getOneArticleById($model->Id);
			$model->CreateBy = $article['CreateBy'];
			$model->Author = $article['Author'];
			$model->CreateTime = $article['CreateTime'];
			$model->Type = ArticleData::TYPE_ARTICLE;
		}
		
		self::instance()->saveArticle($model);	
		self::saveOperateHistory(self::FUNC_CODE_TAG_EDIT, $model->toArray(true,true));
	}
	
	/**
	 * 修改文章地域
	 */
	public static function updateArticleRegion($region,$articleId,$pubStatus){
		self::checkOperation(self::FUNC_CODE_APP_ARTICLE_SAVE);
		self::checkRegionForm($region,$pubStatus);
		self::instance()->updateArticleRegion($region, $articleId);
		self::saveOperateHistory(self::FUNC_CODE_TAG_EDIT, $articleId);
	}
	
	/**
	 * 删除文章（更改状态）
	 * 
	 */
	public static function changeArticleStatus($id, $status){
		self::checkOperation(self::FUNC_CODE_APP_ARTICLE_DELETE);
		self::instance()->updateArticleStatus($id, $status);
		self::saveOperateHistory(self::FUNC_CODE_APP_ARTICLE_DELETE, $status);
	}
	
	
	public static function addActivityArticle($model){
		self::checkOperation(self::FUNC_CODE_APP_ACTIVITY_ADD);
		if(!$model->Title){
			throw new BusinessException('文章标题不能为空');
		}
		if(!$model->PublishTime){
			throw new BusinessException("发布时间不能为空");
		}
		if(!$model->Content && $model->Type == \haibao\app\model\data\Article::TYPE_ARTICLE){
			throw new BusinessException("文章内容不能为空");
		}
		$model->CreateBy = self::getCurrentUser()->Id;
		$model->Author = self::getCurrentUser()->RealName;
		$model->CreateTime = new \DateTime();
		self::instance()->add($model);
		self::saveOperateHistory(self::FUNC_CODE_APP_ACTIVITY_ADD, $model->toArray(true,true));
	}
	
	public static function add($model){
		self::checkOperation(self::FUNC_CODE_APP_ACTIVITY_ADD);
		self::instance()->add($model);
		self::saveOperateHistory(self::FUNC_CODE_APP_ACTIVITY_ADD, $model->toArray(true,true));
	}
	
	public static function save($model){
		self::checkOperation(self::FUNC_CODE_APP_ACTIVITY_UPDATE);
		self::instance()->save($model);
		self::saveOperateHistory(self::FUNC_CODE_APP_ACTIVITY_UPDATE, $model->toArray(true,true));
	}
	
	/**
	 * 显示文章关联标签
	 */
	public static function getRelateType($idArr,$type){
		$retArr = array();
		$row = null;
		if($type == \haibao\app\model\data\Article::STAR_TAG){
			$starData = new \haibao\cms\data\Celebrity();
			$starObj = $starData->getCelebrityById($idArr);
			if( isset($starObj->NameCn) ){
				$row['StarId'] = $starObj->Id;
				$row['StarName'] = $starObj->NameCn;
				$row['StarNameEn'] = $starObj->NameEn;
			}
		}else if($type == \haibao\app\model\data\Article::BRAND_TAG){
			$brandData = new \haibao\cms\data\Brand();
			$brandObj = $brandData->getBrandById($idArr);
			if( isset($brandObj->NameCN) ){
				$row['BrandId'] = $brandObj->Id;
				$row['BrandName'] = $brandObj->NameCN;
				$row['BrandNameEN'] = $brandObj->NameEN;
			}
		}else if($type == \haibao\app\model\data\Article::FASHION_TAG){
			$row = self::instance()->getRelateType($idArr);
		}else if($type == \haibao\app\model\data\Article::EVENT_TAG){
			$eventData = new \haibao\cms\data\Event();
			$eventObj = $eventData->getEventById($idArr);
			if( isset($eventObj->EventName) ){
				$row['EventId'] = $eventObj->Id;
				$row['EventName'] = $eventObj->EventName;
			}
		}
		return $row;
	}
	
	
	/**
	 * 设置资讯点击量
	 * @param unknown_type $articleId
	 * @param int $fromType  来源1APP，2WAP，3PC
	 */
	public static function updateClickNum($articleId,$fromType){
		self::instance()->updateClickNum($articleId,$fromType);
	}
	
	public static function getVoteListByArticleId($articleId){
		if(empty($articleId)){
			throw new BusinessException('参数不正确',self::DATA_ERROR_CODE_EMPTY);
		}
		$data = new \haibao\app\data\ArticleVote();
		return $data->getVoteListByArticleId($articleId);
	}
	
	public static function addShare($articleId,$shareType,$uId){
		self::instance()->addShare($articleId,$shareType,$uId);
	}
	
	
	//APP接口调用
	/**
	 * 用户对文章是否投票，如果有，返回投票项记录
	 * @param unknown_type $articleId
	 * @param unknown_type $userId
	 */
	public static function getVoteListByArticleIdAndUserId($articleId,$userId){
		if(empty($articleId) && empty($userId)){
			throw new BusinessException('参数不正确',self::DATA_ERROR_CODE_EMPTY);
		}
		$data = new \haibao\app\data\ArticleVote();
		return $data->getVoteListByArticleIdAndUserId($articleId, $userId);
	}
	
	/**
	 * 用户添加投票
	 * @param int $articleId
	 * @param int $userId
	 * @param int $voteId
	 */
	public static function addUserVote($articleId, $userId, $voteId){
		if(empty($articleId) && empty($userId) && empty($voteId)){
			throw new BusinessException('参数不正确', self::DATA_ERROR_CODE_EMPTY);
		}
		if(empty($userId)){
			throw new BusinessException('参数不正确', self::DATA_ERROR_CODE_EMPTY);
		}
		$data = new \haibao\app\data\ArticleVote();
		$vote = $data->getVoteById($voteId);
		if(!$vote){
		    throw new BusinessException('参数不正确', self::DATA_ERROR_CODE_EMPTY);
		}elseif($vote && $vote->ArticleId != $articleId){
		    throw new BusinessException('参数不正确', self::DATA_ERROR_CODE_EMPTY);
		}
		
		$resultArr = $data->getVoteListByArticleIdAndUserId($articleId, $userId);
		if(!empty($resultArr) && $resultArr['hasVote'] == "1"){
			throw new BusinessException('你已经参加过投票', self::DATA_ERROR_CODE_EMPTY);
		}
		
		return $data->addUserVote($articleId, $userId, $voteId);
	}
	
	/**
	 * 是否已经为文章点赞
	 */
	public static function isPraised($userId, $articleId){
	    if(empty($articleId) && empty($userId)){
	        throw new BusinessException('参数不正确', self::DATA_ERROR_CODE_EMPTY);
	    }
	    return self::instance()->isPraised($userId, $articleId);
	}
	
	/**
	 * 为文章点赞
	 */
	public static function praiseArticle($userId, $articleId){
	    if(!$userId || !$articleId){
	        throw new BusinessException('参数不正确', self::DATA_ERROR_CODE_EMPTY);
	    }
	    self::instance()->praiseArticle($userId, $articleId);
	}
	
	/**
	 * 取消点赞
	 */
	public static function deletePraise($userId, $articleId){
	    if(!$userId || !$articleId){
	        throw new BusinessException('参数不正确', self::DATA_ERROR_CODE_EMPTY);
	    }
	    self::instance()->deletePraise($userId, $articleId);
	}
	
	private static function checkRegionForm($region,$pubStatus){
		if($pubStatus != 0 && !$region){
			throw new BusinessException('地域不能为空');
		}
	}
	
	public static function getSimilarArticle($articleId, $columnId = null){
	    return self::instance()->getSimilarArticle($articleId, $columnId);
	}
	
	/**
	 * 表单验证
	 * @param \haibao\app\model\data\Article $model
	 */
	private static function checkForm($model){
		if(!$model->Column){
			throw new BusinessException('文章分类不能为空');
		}
		if(!$model->Title){
			throw new BusinessException('文章标题不能为空');
		}
		if(!$model->PublishTime){
			throw new BusinessException("发布时间不能为空");
		}
		if(!$model->ImageId){
			throw new BusinessException("题图不能为空");
		}
		if($model->Published != \haibao\app\model\data\Article::PUBLISHED_NO && !$model->RegionId){
			throw new BusinessException("地域不能为空");
		}
		if(!$model->Content){
			throw new BusinessException("文章内容不能为空");
		}
	}

	/**
	 * 转换传入数据
	 * @param \haibao\app\model\data\Article $model
	 */
	private static function convertData($model){
		if(!empty($model->Star)){
			$model->Star = explode(',', $model->Star);
		}
		if(!empty($model->Brand)){
			$model->Brand = explode(',', $model->Brand);
		}
		if(!empty($model->Fashion)){
			$model->Fashion = explode(',', $model->Fashion);
		}
		if(!empty($model->Area)){
			$model->Area = explode(',', $model->Area);
		}
		if(!empty($model->Event)){
			$model->Event = explode(',', $model->Event);
		}

		if(isset($model->Content)){
			$model->Image = self::getImageByContent($model->Content);
		}
		
		$time = date('Y-m-d H:i:s');
		$model->Status = \haibao\app\model\data\Article::STATUS_ENABLE;
	}
	
	/**
	 * 根据文章内容提取文章图片ID
	 */
	private static function getImageByContent($content){
	    $content = stripcslashes($content);
	    if(preg_match_all('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', $content, $imgMatch)){
	        $oldImgIdArr = array();
	        $imageIdArr = array();
	        $pattern = '/<img[^>]*\s?rel=\"([0-9]+)\"/is';
	        $patternType = '/<img[^>]*\s?type=\"([0-9]+)\"/is';
	        foreach($imgMatch[0] as $key=>$match){
	            if(preg_match($pattern, $match, $rel)){
	                if(preg_match($patternType, $match, $type)){
	                    if(strpos($match, "static.") ===false && strpos($match, "http://mt") === false){
	                        $oldImgIdArr[$rel[1]] = $type[1];
	                    }else{
	                        $imageIdArr[$rel[1]] = $type[1];  //所有操作后  编辑器里的图片
	                    }
	                }
	            }
	        }
	        return $imageIdArr;
	    }
	}
	
	
	public static function getActivity($filter){
		return self::instance()->getOne($filter);
	}
	/**
	 * 获取文章属性
	 */
	public static function getArticleProperty($startData, $endData){
		if(empty($startData)){
			throw new BusinessException('请填入起始时间');
		}
		if(empty($endData)){
			$endData = date("Y-m-d",strtotime("$endData   +1   day"));
		}
		if($startData > $endData){
			throw new BusinessException('起始时间不能大于结束时间');
		}
		$endData = date("Y-m-d",strtotime("$endData   +1   day"));
		$articleProperty = new ArticlePropertyData();
		return  $articleProperty->getArticleProperty($startData, $endData);
	}
	
	public static function getArticlePropertyByArticleId($ids){
		$articleProperty = new ArticlePropertyData();
		return $articleProperty->getArticlePropertyByArticleId($ids);
	}
	
}
